package com.guqj.nio.netty.pstack.util;

import io.netty.buffer.ByteBuf;

import java.io.IOException;

import org.jboss.marshalling.Unmarshaller;

import com.guqj.nio.netty.serialization.marshalling.MarshallingCodeCFactory;

public class NettyMarshallingDecoder {

	private Unmarshaller unmarshaller;

	public NettyMarshallingDecoder() throws IOException {
		unmarshaller = MarshallingCodeCFactory.buildUnMarshalling();
	}

	public Object decode(ByteBuf in) throws IOException, ClassNotFoundException {
		int objectsize = in.readInt();
		ByteBuf buf = in.slice(in.readerIndex(), objectsize);
		ChannelBufferByteInput input = new ChannelBufferByteInput(buf);
		try {
			unmarshaller.start(input);
			Object obj = unmarshaller.readObject();
			unmarshaller.finish();
			in.readerIndex(in.readerIndex() + objectsize);
			return obj;
		} finally {
			unmarshaller.close();
		}
	}
}
